import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from flask import g
from flask import render_template
from flask_wtf.csrf import CSRFProtect, generate_csrf
from flask_session import Session
from config import config_dict
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis

from info.utits.common import do_index_class, user_login_data


def setup_log(config_name):
    logging.basicConfig(level=config_dict[config_name].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


db = SQLAlchemy()

# 初始化redis对象(全局对象),并且声明类型
redis_store = None  # type:StrictRedis


def create_app(config_name):
    setup_log(config_name)
    app = Flask(__name__)
    config_class = config_dict[config_name]
    app.config.from_object(config_class)

    # 创建redis数据库对象
    global redis_store
    redis_store = StrictRedis(host=config_class.REDIS_HOST,
                              port=config_class.REDIS_PORT,
                              db=config_class.REDIS_NUM,
                              decode_responses=True)
    # 创建数据库对象
    # 懒加载思想,延迟加载
    db.init_app(app)

    # csrf = CSRFProtect(app)

    @app.after_request
    def set_csrftoken(response):
        # 生成csrf_token的值
        csrf_token = generate_csrf()
        # 将csrf_token存入cookie中
        response.set_cookie("csrf_token",csrf_token)
        return response

    @app.errorhandler(404)
    @user_login_data
    def error_handler(e):
        """返回错误页面"""
        user = g.user
        data = {
            "user_info":user.to_dict() if user else None
        }

        return render_template("news/404.html",data=data)


    # 初始化拓展Session对象
    Session(app)
    # 在注册蓝图的时候在来导入(延迟导入解决循环导入文件)
    from info.modules.index import index_bp
    # 注册首页的蓝图对象
    app.register_blueprint(index_bp)

    from info.modules.passport import passport_bp
    app.register_blueprint(passport_bp)

    from info.modules.news import news_bp
    app.register_blueprint(news_bp)

    from info.modules.profile import profile_bp
    app.register_blueprint(profile_bp)

    from info.modules.admin import admin_bp
    app.register_blueprint(admin_bp)

    app.add_template_filter(do_index_class)
    # print("app")

    return app
